package gui.edt.swingutilities;

import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;

public class Main {
	public static void main(String[] args) {
		final JProgressBar progressBar = new JProgressBar(0, 100);

		final CounterTask task = new CounterTask();
		task.addPropertyChangeListener(new PropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent evt) {
				if ("progress".equals(evt.getPropertyName())) {
					progressBar.setValue((Integer) evt.getNewValue());
				}
			}
		});
		JButton startButton = new JButton("Start");
		startButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				task.execute();
			}
		});

		JButton cancelButton = new JButton("Cancel");
		cancelButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				task.cancel(true);
			}
		});

		JPanel buttonPanel = new JPanel();
		buttonPanel.add(startButton);
		buttonPanel.add(cancelButton);

		JPanel cp = new JPanel();
		LayoutManager layout = new BoxLayout(cp, BoxLayout.Y_AXIS);
		cp.setLayout(layout);
		cp.add(buttonPanel);
		cp.add(progressBar);

		JFrame frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setContentPane(cp);
		frame.pack();
		frame.setVisible(true);
	}
}

class CounterTask extends SwingWorker<Integer, Double> {
	int DELAY = 100;

	@Override
	protected Integer doInBackground() throws Exception {
		int i = 0;
		int count = 100; 
		while (!isCancelled() && i < count) {
			i++;
			publish(new Double[] { (double) i });
			setProgress(i);
			Thread.sleep(DELAY);
		}
		return count;
	}

	protected void process(List<Double> chunks) {
		System.out.println(chunks);
	}

	@Override
	protected void done() {
		if (isCancelled())
			System.out.println("Cancelled !");
		else
			System.out.println("Done !");
	}
}